package com.chenjj.java.test.juc;

import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.locks.LockSupport;

public class ParkUnparkTester {

    @Test
    public void test1() throws IOException {
        final Thread boyThread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("boy: 我要吃鸡");
                LockSupport.park(this);
                System.out.println("boy: park1");
                LockSupport.park(this); // 第二次会阻塞住，因为只有一个permit
                System.out.println("boy: park2");
                System.out.println("boy: 开始吃鸡了");
            }
        });

        Thread girlThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("girl: 允许");
                LockSupport.unpark(boyThread); // unpark两次，但是permit不会叠加
                LockSupport.unpark(boyThread);
            }
        });

        boyThread.start();
        girlThread.start();

        System.in.read();
    }


    @Test
    public void test2() throws IOException {
        final Thread boyThread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("boy: 我要吃鸡");
                LockSupport.park(this);
                System.out.println("boy: park1");
                LockSupport.park(this); // 第二次会阻塞住，因为只有一个permit
                System.out.println("boy: park2");
                System.out.println("boy: 开始吃鸡了");
            }
        });

        Thread girlThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("girl: 允许");
                LockSupport.unpark(boyThread); // unpark两次，但是permit不会叠加
                LockSupport.unpark(boyThread);

                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                LockSupport.unpark(boyThread);//此时unpark可以解锁boyThread的第二次park阻塞
            }
        });

        boyThread.start();
        girlThread.start();

        System.in.read();
    }
}
